// Package service @program: rankinglist
//@author: edte
//@create: 2021-12-29 16:26
package service

import (
	"context"
	"fmt"
	"net/http"
	leaderboard "rankinglist/config"
	"rankinglist/database"
	"rankinglist/log"
	"strconv"
)

type Rank struct {
	leaderboard.UnimplementedProdScoreBoardServiceServer
}

func (r Rank) StartDataMigration(ctx context.Context, in *leaderboard.StartDataMigrationRequest) (response *leaderboard.StarDataMigrationResponse, err error) {
	response = &leaderboard.StarDataMigrationResponse{}
	err = database.MigrationDataToMysql()
	if err != nil {
		writeLog, err2 := log.WriteLog(ctx, "ranklist", "StartDataMigration", "userId:"+strconv.Itoa(int(in.UserId)), "Error", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
			//return nil, err
		}
		response.Status = http.StatusBadRequest
		return response, err
	}
	response.Status = http.StatusOK
	return response, err
}
func (r Rank) GetUserForm(cxt context.Context, in *leaderboard.ProdScoreBoardRequest) (response *leaderboard.ProdScoreBoardResponse, err error) {
	response = &leaderboard.ProdScoreBoardResponse{
		Ranking: make(map[int32]string),
	}
	//database.MigrationDataToMysql()
	score, err := database.QueryPlayerScore(cxt, in.BoardName, int(in.StartPage), int(in.EndPage))
	if err != nil {

		writeLog, err2 := log.WriteLog(cxt, "ranklist", "GetUserForm", "boardname"+in.BoardName, "Warning", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
			return nil, err
		}
		response.Status = http.StatusBadRequest
		response.Ranking = nil
		return response, err
	}
	for i, s := range score {
		response.Ranking[int32(i+1)] = s
	}

	writeLog, err2 := log.WriteLog(cxt, "ranklist", "GetUserForm", "boardname"+in.BoardName, "Debug", "The query is successful")
	if writeLog == 200 {
		fmt.Println("成功写入日志")
	}
	if err2 != nil {
		fmt.Println("写入日志失败")
		return nil, err
	}
	response.Status = http.StatusOK
	return response, err
}
